package com.example.controller;
import java.time.LocalDateTime;


import com.example.common.Result;
import com.example.constant.UserConstant;
import com.example.model.dto.UserDeleteRequestDTO;
import com.example.model.dto.UserLoginRequestDTO;
import com.example.model.dto.UserRegisterRequestDTO;
import com.example.model.po.User;
import com.example.model.vo.UserSearchVO;
import com.example.service.IUserService;



import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;


/**
 * <p>
 * 用户 前端控制器
 *
 * @author LinHui
 * @since 2024-03-28
 */
@RestController
@Slf4j
@RequestMapping("/user")
//@Api("用户登录注册类")
public class UserController {


    @Resource
    private IUserService userService;




    /**
     *
     * 用户注册
     *
     * @param userRegisterRequestDTO 接受dto
     * @return 返回用户id
     */
    //@ApiOperation("用户注册")
    @PostMapping("/register")
    public Result<Long> userRegister(@RequestBody UserRegisterRequestDTO userRegisterRequestDTO) {

        if (userRegisterRequestDTO == null) {
            return Result.error("传入用户数据为空");
        }

        String userAccount = userRegisterRequestDTO.getUserAccount();
        String userPassword = userRegisterRequestDTO.getUserPassword();
        String checkPassword = userRegisterRequestDTO.getCheckPassword();

        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword)) {
            return Result.error("账号/密码/校验密码为空");
        }
        long id = userService.userRegister(userAccount, userPassword, checkPassword);


        return Result.success(id);
    }


    /**
     *
     * 用户登录
     *
     * @param userLoginRequestDTO 用户传参
     * @param request http
     * @return 返回脱敏用户信息
     */
    //@ApiOperation("用户登录")
    @PostMapping("/login")
    public Result<User> userLogin(@RequestBody UserLoginRequestDTO userLoginRequestDTO, HttpServletRequest request) {
        if (userLoginRequestDTO == null) {

            return Result.error("传入用户数据为空");
        }

        String userAccount = userLoginRequestDTO.getUserAccount();
        String userPassword = userLoginRequestDTO.getUserPassword();


        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            return Result.error("账号/密码为空");
        }
        User user = userService.userLogin(userAccount, userPassword, request);

        return Result.success(user);
    }


    /**
     *
     * 根据用户名查询
     *
     * @param userName
     * @return
     */
    @GetMapping("/search")
    public Result<List<UserSearchVO>> searchUser(String userName, HttpServletRequest request) {
        //鉴定权限
        if (!isAdmin(request)) {
            return Result.error("权限不足");
        }


        log.info("要查询的用户名： {}", userName);
        return Result.success(userService.lambdaQuery().
                like(userName != null, User::getUsername, userName).
                list().
                stream().
                map(user -> {
                    UserSearchVO userSearchVO = new UserSearchVO();
                    //脱敏
                    BeanUtils.copyProperties(userService.getSafteUser(user), userSearchVO);
                    return userSearchVO;

                }).collect(Collectors.toList()));
    }


    @PostMapping("/delete")
    public Result<Boolean> deleUser(@RequestBody UserDeleteRequestDTO userDeleteRequestDTO, HttpServletRequest request) {
        log.info("进入信息删除, id{}", userDeleteRequestDTO.getId());
        //if (id == null) {
        //    return false;
        //}
        //鉴定权限
        if (!isAdmin(request)) {
            return Result.error("权限不足，无法删除用户");
        }

        log.info("要删除的id: {}", userDeleteRequestDTO.getId());
        if (userDeleteRequestDTO.getId() <= 0) {
            return Result.error("要删除的用户id小于0，错误");
        }

        log.info("要删除的id: {}", userDeleteRequestDTO.getId());
        boolean remove = userService.lambdaUpdate().
                eq(User::getId, userDeleteRequestDTO.getId()).
                remove();

        return Result.success(remove);

    }


    /**
     *
     * 获取用户登录状态
     *
     * @param request
     * @return
     */
    @GetMapping("/current")
    public Result<User> getCurrentUser(HttpServletRequest request) {
        User user = (User)request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);

        if (user == null) {
            return Result.error("session中用户状态为空");
        }

        // todo 这里后来要确认用户状态，如果用户是被封号的，那么是不能登录，没有状态的
        //脱敏
        return Result.success(userService.getSafteUser(userService.lambdaQuery().eq(User::getId, user.getId()).one()));
    }


    /**
     *
     * 退出登录
     *
     * @param request
     * @return
     */
    @PostMapping("/outLogin")
    public Result<Boolean> outLogin(HttpServletRequest request) {
        request.getSession().removeAttribute(UserConstant.USER_LOGIN_STATE);
        return Result.success(true);
    }


    /**
     *
     * 鉴定权限
     *
     * @param request
     * @return
     */
    private boolean isAdmin(HttpServletRequest request) {
        User user = (User)request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);

        // todo 后期需要处理，这里需要抛出异常
        if (user == null || user.getUserRole() != UserConstant.ADMIN_ROLE) {
            log.info("权限不够，仅仅管理员可操作");
            return false;
        }

        return true;
    }

}
